package cn.com.yang.datastruct.link;

import java.util.Iterator;

/**
 * @since  2023.08.13
 * @param <T>
 */
public class LinkListWithIterator<T> implements ListWithItratorInterface<T>{
    private Node head;
    private Node tail;
    private int size;

    private class Node{
        private T data;
        private Node next;
        public Node(T data){
            this.data = data;
        }

        @Override
        public String toString() {
            return "Node{" +
                    "data=" + data +
                    ", next=" + next +
                    '}';
        }
    }

    private class IteratorForLinkList implements Iterator<T>{
        private Node nextNode;
        public IteratorForLinkList (){
            nextNode = head;
        }
        @Override
        public boolean hasNext() {
            return nextNode!=null;
        }

        @Override
        public T next() {
            if (hasNext()){
                Node rs = nextNode;
                nextNode = nextNode.next;
                return rs.data;
            }else {
                return null;
            }
        }
    }
    @Override
    public int getSize() {
        return 0;
    }

    @Override
    public void addHead(T data) {
        Node newNode = new Node(data);
        if (size==0){
            head = newNode;
            tail=newNode;
            size++;
        }else {
            newNode.next = head;
            head =newNode;
            size++;
        }
    }

    @Override
    public void addTail(T data) {
        Node newNode = new Node(data);
        if (size==0){
            head = newNode;
            tail=newNode;
            size++;
        }else {
            tail.next = newNode;
            tail =newNode;
            size++;
        }
    }

    @Override
    public Iterator getIterator() {
        return new IteratorForLinkList();
    }
}
